package com.monkeybrother.thread.semaphore;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.monkeybrother.thread.factory.SmartDeviceTrackFileThreadPoolSingleton;
import lombok.SneakyThrows;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Desc
 * @Author houruiyang
 * @Date 2022/3/3
 **/
public class ExcelModelListener implements ReadListener<SemaphoreTest> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 30000;
    /**
     * 缓存的数据
     */
    private List<SemaphoreTest> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);



    @Override
    public void invoke(SemaphoreTest data, AnalysisContext context) {

        cachedDataList.add(data);

    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @SneakyThrows
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        Semaphore semaphore = new Semaphore(200);
        CountDownLatch downLatch = new CountDownLatch(cachedDataList.size());
//        System.out.println(cachedDataList.size());
        long beginTime = System.currentTimeMillis();
        AtomicInteger count = new AtomicInteger();
        cachedDataList.forEach(v -> {
            SmartDeviceTrackFileThreadPoolSingleton.getInstance().execute(() ->{
                try {
                    semaphore.acquire();

                    TimeUnit.SECONDS.sleep(1);
                    downLatch.countDown();
                    System.out.println("递减之后的 " + downLatch.getCount());
                    count.getAndIncrement();
                    System.out.println("count ===" + count.get());

                    System.out.println("活跃线程数"  + SmartDeviceTrackFileThreadPoolSingleton.getInstance().getActiveCount());
                    System.out.println("队列数"  + SmartDeviceTrackFileThreadPoolSingleton.getInstance().getQueue().size());

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            });

        });
        downLatch.await();
        long endTime = System.currentTimeMillis();
        System.out.println("总共" + cachedDataList.size() +"条数据， 一共执行了 " + count.get() +"个任务, 消耗时间：" + (endTime - beginTime));
        SmartDeviceTrackFileThreadPoolSingleton.getInstance().shutdown();
    }


}
